from json import loads, dumps
from datetime import date
import os

def conditionInput(ask1, ask2 = "", err = "Error, please reinput.", cond = lambda x: True):
	if ask2 == "":
		ask2 = ask1
	ret = input(ask1)
	while not cond(ret):
		print(err)
		ret = input(ask2)
	return ret

def optSelect(opt):
	for i in range(0, len(opt)):
		print(i+1, ":\t", opt[i], sep = "")
	return opt[int(conditionInput("Enter Choice: ", "Enter Choice Again: ", "Out of range or unrecognizable.", lambda x: 1 <= int(x) <= len(opt))) - 1]

def loadFromFile(fnm):
	with open(fnm) as f:
		return f.read()

def saveToFile(fnm, a):
	with open(fnm, "w") as f:
		f.write(a)

def load():
	global blog, categ, tag
	blog = loads(loadFromFile("source/blog.json"))
	categ = loads(loadFromFile("source/categ.json"))
	tag = loads(loadFromFile("source/tag.json"))

def save():
	global blog, categ, tag
	saveToFile("source/blog.json", dumps(blog))
	saveToFile("source/categ.json", dumps(categ))
	saveToFile("source/tag.json", dumps(tag))

def addTag():
	tmp = {}
	tmp["name"] = conditionInput("Input name: ")
	tmp["headline"] = conditionInput("Input headline: ", cond = lambda x: x.isalnum())
	global tag
	tag["Tag"].append(tmp)
	return tmp["name"]

def addCateg():
	tmp = {}
	tmp["name"] = conditionInput("Input name: ")
	tmp["description"] = conditionInput("Input description: ")
	tmp["headline"] = conditionInput("Input headline: ", cond = lambda x: x.isalnum())
	global categ
	categ["Categ"].append(tmp)
	return tmp["name"]

def addBlog():
	tmp = {}
	tmp["title"] = conditionInput("Input title: ")
	tmp["filename"] = conditionInput("Input filename: ", err = "File not found.", cond = lambda x: os.path.exists("source/post/" + x + ".md")) + ".md"
	tmp["date"] = date.today().isoformat()
	tmp["headline"] = conditionInput("Input headline: ", cond = lambda x: x.isalnum())
	tmp["category"] = optSelect(["+ New One"] + [x["name"] for x in categ["Categ"]])
	print("Choose category:")
	if tmp["category"] == "+ New One":
		tmp["category"] = addCateg()
	tglst = []
	print("Choose tag:")
	while True:
		tglst.append(optSelect(["+ New One", "- Finish"] + [x["name"] for x in tag["Tag"]]))
		if tglst[-1] == "+ New One":
			tglst[-1] = addTag()
		if tglst[-1] == "- Finish":
			tglst.pop()
			break
	tmp["tags"] = tglst
	global blog
	blog["Blog"].append(tmp)

if __name__ == "__main__":
	blog = None
	categ = None
	tag = None
	load()
	while True:
		a = optSelect(["Add New Blog", "Add New Category", "Add New Tag", "Save", "Generate", "Clear", "View", "Quit"])
		if a == "Add New Blog":
			addBlog()
		if a == "Add New Category":
			addCateg()
		if a == "Add New Tag":
			addTag()
		if a == "Save":
			save()
		if a == "Generate":
			os.system("python twister.py")
		if a == "Clear":
			blog = {"Blog": []}
			categ = {"Categ": []}
			tag = {"Tag": []}
		if a == "View":
			os.system("start output/index.html")
		if a == "Quit":
			break
	